/***************************************
 *
 *       主界面
 *
 ***************************************/

#include "kithara_widget.h"
#include <QButtonGroup>
#include <QDebug>
#include <QMessageBox>
#include "ui_kithara_widget.h"

KitharaWidget::KitharaWidget(QWidget *parent): QWidget(parent), ui(new Ui::KitharaWidget)
{
    ui->setupUi(this);

    Init();
    OnConnected();
}

KitharaWidget::~KitharaWidget()
{
    is_running = false;
    ExitApp();
    delete ui;
}

void KitharaWidget::Init()
{
    if (GetKitharaSystemInfo(system_info_) != KS_OK) {
        QMessageBox::information(this, "Tip", "Init Error，Unable to continue ...");
        return;
    }

    if (!system_info_.net_work_list.isEmpty()) { ui->comboBox_network->addItems(system_info_.net_work_list); }
    else { ui->comboBox_network->addItem("no fund network device"); }

    ui->spinBox_processor_cpu->setMinimum(0);
    ui->spinBox_processor_cpu->setMaximum(system_info_.total_cpu_count - 1);
    ui->spinBox_processor_cpu->setValue(system_info_.total_cpu_count - 1);

    ui->label_total_cpus->setText(QString::number(system_info_.total_cpu_count));
    ui->label_shared_cpus->setText(QString::number(system_info_.shared_cpu_count));
    ui->button_start->setDisabled(false);

    ui->spinBox_slave_count->setValue(1);
}

void KitharaWidget::OnConnected()
{
    connect(ui->button_start, &QPushButton::clicked, this, &KitharaWidget::OnButtonStartClicked);
    connect(ui->send_sdo, &QPushButton::clicked, this, &KitharaWidget::OnButtonSendSDOClicked);
    connect(ui->read_sdo, &QPushButton::clicked, this, &KitharaWidget::OnButtonReadSDOClicked);
}

void KitharaWidget::paintEvent(QPaintEvent *event) { QWidget::paintEvent(event); }

void KitharaWidget::OnButtonStartClicked()
{
    if (ui->comboBox_network->currentText() == "no fund network device") {
        QMessageBox::warning(this, "Tip", "No Fund NetWork Device!");
        return;
    }

    int processor = ui->spinBox_processor_cpu->value();

    QString file_path;
    if (ui->lineEdit->text().isEmpty()) { file_path = R"(C:\TwinCAT\3.1\Config\Io\EtherCAT)"; }
    else { file_path = ui->lineEdit->text(); }

    if (ui->spinBox_slave_count->value() == 0) {
        QMessageBox::warning(this, "Tip", "The number of slaves is 0!");
        return;
    }

    if (StartRunning(processor, ui->comboBox_network->currentIndex(), file_path.toStdString()) != KS_OK) { QMessageBox::warning(this, "Tip", "Running  Failed!"); }
    else {
        ui->button_start->setDisabled(true);
        is_running = true;
    }
}

void KitharaWidget::OnButtonSendSDOClicked()
{
    byte data[100];
    //for (byte &d: data) { d = 1; }

    SDO_Download(0x30A2, data, 100);
}

void KitharaWidget::OnButtonReadSDOClicked()
{
    int size = 0;
    byte data[2501];
    SDO_GetData(0x30A2, data, size);
}
